/*
 * Title: 树（Tree）
 * Author: Yuanshun L
 * Created : 23-otc-2021
 */

#include<cstdio>
#include<iostream>
#include<string>
#include<sstream>
#include<cstring>
using namespace std;

#define MAXN 10000+5
int in[MAXN];
int post[MAXN];
int rchild[MAXN];
int lchild[MAXN];
int n;

// 读取一行序列
bool read_seq(int *arr){
    string line;
    if(getline(cin,line)){
        stringstream ss(line);
        int val;
        n = 0;
        while(ss>>val){
            arr[n] = val;
            n++;
        }
        return true;
    }
    return false;
}

// 构建二叉树
int build(int x1,int y1,int x2, int y2){

    if(x1<=y1){
        int pos = x1,size,weight;
        weight = post[y2];
        while(pos<=y1 && in[pos]!=weight) pos++;


        size = pos-x1;

        lchild[weight] = build(x1,pos-1,x2,x2+size-1);
        rchild[weight] = build(pos+1,y1,x2+size,y2-1);

        return weight;

    }
    return 0;
}

// 深度优先遍历二叉树
void print(int root){
    cout<<root<<" ";
    if(lchild[root]>0)
        print(lchild[root]);
    if(rchild[root]>0)
        print(rchild[root]);
}

// path为路劲权值之和，res为最小路径上叶子结点的值
void get_least_path_value(int root,int sum, int &path,int &res){
    // 找到了一个叶子结点
    if(!(lchild[root] || rchild[root])){
        sum += root;
        // 找到了第一条路径
        if(path == -1){
            path = sum; res = root;
        }
        else{
            if(sum < path){
                path = sum; res = root;
            }
            else if(sum == path && root < res)
                res = root;
        }
    }
    else{
        if(lchild[root]){
            get_least_path_value(lchild[root],sum+root,path,res);
        }
        if(rchild[root]){
            get_least_path_value(rchild[root],sum+root,path,res);
        }
    }

}

int main(){

    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    string s1,s2;
    while(read_seq(in) && read_seq(post)){
        // 深度优先遍历构建二叉树
        int root =  build(0,n-1,0,n-1);
        int path=-1,res;
        get_least_path_value(root,root,path,res);
        cout<<res<<endl;

    }
    return 0;
}
